//
//  QuickLoansStep2View.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/12/6.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

@objc protocol QuickLoansStep2ViewDelegate {
    @objc optional func previousStepAction() //上一步
    @objc optional func applyNowAction() //立即申请
}

class QuickLoansStep2View: UIView {
    
    var delegate : QuickLoansStep2ViewDelegate?
    
    fileprivate let scrollView = UIScrollView()
    
    fileprivate let titleLabel = UILabel()
    fileprivate let lineView = UIView()
    
    fileprivate let houseView = LoanSelectView() //房产
    fileprivate let carView = LoanSelectView() //车辆
    fileprivate let insuranceView = LoanSelectView() //保险
    
    fileprivate let houseDetailsView = QuickLoanHouseView() //房产详情
    fileprivate let carDetailsView = QuickLoanCarView() //车辆详情
    
    fileprivate let previousButton = UIButton() //上一步
    fileprivate let applicationButton = UIButton() //立即申请
    
    fileprivate let labelTypeView = QuickLoanSelectView() //标签类型选择
    fileprivate var preLoanSelectView = LoanScreenView() //记录上一个点击的按钮
    
    fileprivate var houseProvince = "" //购房省份
    fileprivate var carProvince = "" //购车省份
    
    var model = [String:String]() //相关数据

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.white
        
        scrollView.showsVerticalScrollIndicator = true
        scrollView.bounces = false
        scrollView.delegate = self
        self.addSubview(scrollView)
        
        titleLabel.text = "step 2 > " + financialSupport
        titleLabel.textColor = UIColor.red
        titleLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 18))
        scrollView.addSubview(titleLabel)
        
        lineView.backgroundColor = UIColor.red
        scrollView.addSubview(lineView)
        
        houseView.tag = 1
        houseView.delegate = self
        houseView.title = hasHouse
        scrollView.addSubview(houseView)
        
        houseDetailsView.isHidden = true
        houseDetailsView.delegate = self
        scrollView.addSubview(houseDetailsView)
        
        carView.tag = 2
        carView.delegate = self
        carView.title = hasCar
        scrollView.addSubview(carView)
        
        carDetailsView.isHidden = true
        carDetailsView.delegate = self
        scrollView.addSubview(carDetailsView)
        
        insuranceView.tag = 3
        insuranceView.delegate = self
        insuranceView.title = hasInsurance
        scrollView.addSubview(insuranceView)
        
        previousButton.setTitle(previousStep, for: .normal)
        previousButton.backgroundColor = UIColor.red
        previousButton.layer.cornerRadius = 5
        previousButton.layer.masksToBounds = true
        previousButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        previousButton.addTarget(self, action: #selector(previousStepAction), for: .touchUpInside)
        scrollView.addSubview(previousButton)
        
        applicationButton.setTitle(applyNow, for: .normal)
        applicationButton.backgroundColor = UIColor.red
        applicationButton.layer.cornerRadius = 5
        applicationButton.layer.masksToBounds = true
        applicationButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        applicationButton.addTarget(self, action: #selector(applyNowAction), for: .touchUpInside)
        scrollView.addSubview(applicationButton)
        
        labelTypeView.delegate = self
        scrollView.addSubview(labelTypeView)
        
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(RATIO_H(maxNum: 20))
            make.centerX.equalToSuperview()
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(5)
            make.left.right.equalTo(self)
            make.height.equalTo(1)
        }
        
        houseView.snp.makeConstraints { (make) in
            make.top.equalTo(lineView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(40)
        }
        
        houseDetailsView.snp.makeConstraints { (make) in
            make.top.equalTo(houseView.snp.bottom)
            make.left.right.equalTo(self)
            make.height.equalTo(0)
        }
        
        carView.snp.makeConstraints { (make) in
            make.top.equalTo(houseDetailsView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(houseView)
        }
        
        carDetailsView.snp.makeConstraints { (make) in
            make.top.equalTo(carView.snp.bottom)
            make.left.right.equalTo(self)
            make.height.equalTo(0)
        }
        
        insuranceView.snp.makeConstraints { (make) in
            make.top.equalTo(carDetailsView.snp.bottom).offset(10)
            make.left.right.equalTo(self)
            make.height.equalTo(carView)
        }
        
        previousButton.snp.makeConstraints { (make) in
            make.top.equalTo(insuranceView.snp.bottom).offset(20)
            make.centerX.equalTo(ScreenW/4)
            make.width.equalTo(ScreenW/3)
            make.height.equalTo(40)
        }
        
        applicationButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(previousButton)
            make.centerX.equalTo(ScreenW/4*3)
            make.width.height.equalTo(previousButton)
        }
        
    }
    
    //MARK: 上一步
    @objc fileprivate func previousStepAction() {
        
        self.delegate?.previousStepAction!()
    }
    
    //MARK: 立即申请
    @objc fileprivate func applyNowAction() {
        
        if houseView.isYes == "" {
            KMTool.showText(_text: hasHouse)
            return
        }else if houseView.isYes == "1" {
            
            if houseDetailsView.houseProvinceView.text == "" || houseDetailsView.houseProvinceView.text == nil {
                KMTool.showText(_text: selectHouseProvince)
                return
            }
            
            if houseDetailsView.houseCityView.text == "" || houseDetailsView.houseCityView.text == nil {
                KMTool.showText(_text: selectHouseCity)
                return
            }
            
            if houseDetailsView.houseTypeView.text == "" || houseDetailsView.houseTypeView.text == nil {
                KMTool.showText(_text: selectHouseProperties)
                return
            }
            
            if houseDetailsView.houseYearView.text == "" || houseDetailsView.houseYearView.text == nil {
                KMTool.showText(_text: selectBuildYear)
                return
            }
            
            if houseDetailsView.houseAreaView.text == "" || houseDetailsView.houseAreaView.text == nil {
                KMTool.showText(_text: selectBuildArea)
                return
            }
            
            if houseDetailsView.housePriceView.text == "" || houseDetailsView.housePriceView.text == nil {
                KMTool.showText(_text: selectHousePrice)
                return
            }
            
            if houseDetailsView.houseGaveView.isYes == "" {
                KMTool.showText(_text: hasGave)
                return
            }
        }
        
        if carView.isYes == "" {
            KMTool.showText(_text: hasCar)
            return
        }else if carView.isYes == "1" {
            
            if carDetailsView.carProvinceView.text == "" || carDetailsView.carProvinceView.text == nil {
                KMTool.showText(_text: selectCarProvince)
                return
            }
            
            if carDetailsView.carCityView.text == "" || carDetailsView.carCityView.text == nil {
                KMTool.showText(_text: selectCarCity)
                return
            }
            
            if carDetailsView.carPriceView.text == "" || carDetailsView.carProvinceView.text == nil {
                KMTool.showText(_text: selectCarPrice)
                return
            }
            
            if carDetailsView.carTimeView.text == "" || carDetailsView.carTimeView.text == nil {
                KMTool.showText(_text: selectCarTime)
                return
            }
            
            if carDetailsView.seatView.isYes == "" {
                KMTool.showText(_text: hasNineSeats)
                return
            }
        }
        
        if insuranceView.isYes == "" {
            KMTool.showText(_text: hasInsurance)
            return
        }
        
        self.delegate?.applyNowAction!()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension QuickLoansStep2View : LoanSelectViewDelegate {
    
    //MARK: 是否选中
    func selectLoanType(currentView: LoanSelectView) {
        
        self.endEditing(true) //隐藏键盘
        
        preLoanSelectView.showSelect = false
        labelTypeView.isHidden = true
        
        switch currentView.tag {
        case 1: //是否有房
            if currentView.isYes == "1" {
                
                model["house"] = yes_title
                
                //添加房产信息
                for (key,value) in houseDetailsView.model {
                    model[key] = value
                }
                
                self.houseDetailsView.isHidden = false
                self.houseDetailsView.snp.remakeConstraints { (make) in
                    make.top.equalTo(self.houseView.snp.bottom).offset(10)
                    make.left.right.equalTo(self)
                    make.height.equalTo(350)
                }
            }else{
                
                //移除房产信息
                for (key,_) in houseDetailsView.model {
                    model.removeValue(forKey: key)
                }
                
                model["house"] = no_title
                
                self.houseDetailsView.isHidden = true
                self.houseDetailsView.snp.remakeConstraints { (make) in
                    make.top.equalTo(self.houseView.snp.bottom)
                    make.left.right.equalTo(self)
                    make.height.equalTo(0)
                }

            }
        case 2: //是否有车
            if currentView.isYes == "1" {
                
                model["car"] = yes_title
                
                //添加车辆信息
                for (key,value) in carDetailsView.model {
                    model[key] = value
                }
                
                self.carDetailsView.isHidden = false
                self.carDetailsView.snp.remakeConstraints { (make) in
                    make.top.equalTo(self.carView.snp.bottom).offset(10)
                    make.left.right.equalTo(self)
                    make.height.equalTo(250)
                }
            }else{
                model["car"] = no_title
                
                //移除车辆信息
                for (key,_) in carDetailsView.model {
                    model.removeValue(forKey: key)
                }
                
                self.carDetailsView.isHidden = true
                self.carDetailsView.snp.remakeConstraints { (make) in
                    make.top.equalTo(self.carView.snp.bottom)
                    make.left.right.equalTo(self)
                    make.height.equalTo(0)
                }
            }
        case 3: //是否购买保险
            if currentView.isYes == "1" {
                model["insurence"] = yes_title
            }else{
                model["insurence"] = no_title
            }
        default:
            break
        }
        
        self.layoutIfNeeded()
        scrollView.contentSize = . init(width: ScreenW, height: applicationButton.frame.maxY + 20)
    }
}

extension QuickLoansStep2View :  QuickLoanHouseViewDelegate,QuickLoanCarViewDelegate,QuickLoanSelectViewDelegate {
    
    //MARK: 选择贷款标签
    func selectLoanType(selectType: String, title: String) {
        
        preLoanSelectView.showSelect = false
        labelTypeView.isHidden = true
        
        switch selectType {
        case "1": //购房省份
            houseDetailsView.houseProvinceView.text = title
            houseDetailsView.houseCityView.text = ""
            houseProvince = title
            model["house_province"] = houseDetailsView.houseProvinceView.text
            model["house_city"] = houseDetailsView.houseCityView.text
        case "2": //购房城市
            houseDetailsView.houseCityView.text = title
            model["house_city"] = houseDetailsView.houseCityView.text
        case "3": //房产性质
            houseDetailsView.houseTypeView.text = title
            model["house_quality"] = houseDetailsView.houseTypeView.text
        case "4": //房产时间
            houseDetailsView.houseYearView.text = title
            model["house_time"] = houseDetailsView.houseYearView.text
        case "5": //车辆省份
            carDetailsView.carProvinceView.text = title
            carDetailsView.carCityView.text = ""
            carProvince = title
            model["car_province"] = carDetailsView.carProvinceView.text
            model["car_city"] = carDetailsView.carCityView.text
        case "6": //车辆城市
            carDetailsView.carCityView.text = title
            model["car_city"] = carDetailsView.carCityView.text
        default:
            break
        }
    }
    
    //MARK: 显示选择框
    func showHouseSelectView(currentView: LoanScreenView) {
        
        self.showSelectText(currentView: currentView)
    }
    
    //MARK: 显示选择框
    func showCarSelectView(currentView: LoanScreenView) {
        
        self.showSelectText(currentView: currentView)
    }
    
    //MARK: 显示弹出款内容
    func showSelectText(currentView: LoanScreenView) {
        
        self.endEditing(true) //隐藏键盘
        
        labelTypeView.selectType = "\(currentView.tag)"
        
        if preLoanSelectView != currentView {
            preLoanSelectView.showSelect = false
            preLoanSelectView = currentView
        }
        
        currentView.showSelect = !currentView.showSelect
        
        if currentView.showSelect {
            labelTypeView.isHidden = false
        }else{
            labelTypeView.isHidden = true
        }
        
        var height:CGFloat = 0
        
        switch currentView.tag {
        case 1: //购房省份
            labelTypeView.dataArray = KMTool.getAllProvince()
        case 2: //购房城市
            labelTypeView.dataArray = KMTool.getCityForProvince(province: houseProvince)
        case 3: //房产性质
            labelTypeView.dataArray = [unknown,commercialHouse,commercialUseHouse,housing,relocationRoom,relocationAndRehousingRoom,apartment,smallPropertyRoom,CCBDeliveryRoom,militaryDeliveryRoom,servicedApartments,condoHotels,villa]
        case 4: //购房时间
            labelTypeView.dataArray = ["2010年之前","2010","2011","2012","2013","2014","2015","2016","2017","2018"]
        case 5: //车辆省份
            labelTypeView.dataArray = KMTool.getAllProvince()
        case 6: //车辆城市
            labelTypeView.dataArray = KMTool.getCityForProvince(province: carProvince)
        default:
            break
        }
        
        var h:CGFloat = 0
        
        if currentView.tag < 5 {
            height += houseDetailsView.frame.origin.y
            h = CGFloat(labelTypeView.dataArray.count * 40) > (ScreenH - currentView.frame.maxY - height) ? (ScreenH - currentView.frame.maxY - height) :  CGFloat(labelTypeView.dataArray.count * 40)
        }else{
            height += carDetailsView.frame.origin.y
            h = CGFloat(labelTypeView.dataArray.count * 40) > (scrollView.contentSize.height - currentView.frame.maxY - height) ? (scrollView.contentSize.height - currentView.frame.maxY - height) :  CGFloat(labelTypeView.dataArray.count * 40)
        }
        
        labelTypeView.snp.remakeConstraints { (make) in
            make.top.equalTo(currentView.textView.snp.bottom)
            make.left.right.equalTo(currentView.textView)
            make.height.equalTo(h)
        }
    }
    
}

extension QuickLoansStep2View : UIScrollViewDelegate {
    
    //MARK: 滑动时取消选择框
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if !labelTypeView.isHidden {
            labelTypeView.isHidden = true
            preLoanSelectView.showSelect = false
        }
    }
}
